/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package io.skywalking.apm.plugin.ice.v3;

import com.xikang.ice.client.pool.PooledProxyHandler;
import org.apache.skywalking.apm.agent.core.context.CarrierItem;
import org.apache.skywalking.apm.agent.core.context.ContextCarrier;
import org.apache.skywalking.apm.agent.core.context.ContextManager;
import org.apache.skywalking.apm.agent.core.context.tag.Tags;
import org.apache.skywalking.apm.agent.core.context.trace.AbstractSpan;
import org.apache.skywalking.apm.agent.core.context.trace.SpanLayer;
import org.apache.skywalking.apm.agent.core.logging.api.ILog;
import org.apache.skywalking.apm.agent.core.logging.api.LogManager;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.EnhancedInstance;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.InstanceMethodsAroundInterceptor;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.MethodInterceptResult;
import org.apache.skywalking.apm.network.trace.component.OfficialComponent;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class IceV3ExecuteInterceptor implements InstanceMethodsAroundInterceptor {

    private static final ILog LOGGER = LogManager.getLogger(IceV3ExecuteInterceptor.class);

    /**
     * 方法执行前执行
     *
     * @param objInst
     * @param method
     * @param allArguments
     * @param argumentsTypes
     * @param result
     * @throws Throwable
     */
    @Override
    public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments,
                             Class<?>[] argumentsTypes, MethodInterceptResult result) throws Throwable {
        //判断参数
        if (allArguments[0] == null || allArguments[1] == null || allArguments[2] == null) {
            // illegal args, can't trace. ignore.
            return;
        }
        PooledProxyHandler handler = (PooledProxyHandler) objInst;
        String host = handler.getProxyCacheKey().split("-")[0];
        Method proxy = ((Method) allArguments[1]);
        Class<?>[] value = proxy.getParameterTypes();

        String operationName = proxy.getName();

        //获取carrier
        ContextCarrier contextCarrier = new ContextCarrier();
        //创建exit span
        AbstractSpan span = ContextManager.createExitSpan(operationName, contextCarrier, host);
        LOGGER.debug("global trace id :{}", ContextManager.getGlobalTraceId());
        //获取传递ctx
        Map<String, String> ctx = new HashMap<String, String>();
        Object[] methodArgs = (Object[]) allArguments[2];
        //判断最后一个参数传递是否是__ctx
        if (value[value.length-1].getName().equals("java.util.Map")
        && methodArgs[methodArgs.length-1] == null){
            methodArgs[methodArgs.length - 1] = ctx;
        }
        LOGGER.debug("IceV3ExecuteInterceptor.beforeMethod process param :{}", allArguments);

        CarrierItem next = contextCarrier.items();
        LOGGER.debug("IceV3ExecuteInterceptor.beforeMethod next= headkey :{},headvalue :{}", next.getHeadKey(), next.getHeadValue());
        while (next.hasNext()) {
            //传递给下一个服务
            next = next.next();
            ctx.put(next.getHeadKey(), next.getHeadValue());
            LOGGER.trace("IceV3ExecuteInterceptor.beforeMethod afer hasnext next= headkey :{},headvalue :{}", next.getHeadKey(), next.getHeadValue());
        }
        span.setComponent(new OfficialComponent(115, "ice-java"));
        Tags.URL.set(span, host + "/" + operationName);
        SpanLayer.asRPCFramework(span);
    }

    @Override
    public Object afterMethod(EnhancedInstance objInst, Method method, Object[] allArguments,
                              Class<?>[] argumentsTypes, Object ret) throws Throwable {
        LOGGER.debug("IceV3ExecuteInterceptor.afterMethod process");
        ContextManager.stopSpan();
        return ret;
    }

    @Override
    public void handleMethodException(EnhancedInstance objInst, Method method, Object[] allArguments,
                                      Class<?>[] argumentsTypes, Throwable t) {
        LOGGER.debug("IceV3ExecuteInterceptor.handleMethodException process");
        AbstractSpan activeSpan = ContextManager.activeSpan();
        activeSpan.log(t);
        activeSpan.errorOccurred();
    }
}
